/*
 * Copyright (c) 2012 Johan Fylling
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy 
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights 
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 * copies of the Software, and to permit persons to whom the Software is 
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in 
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 * THE SOFTWARE.
 */

part of engine;


/**
 * Narrow-phase Collision Detector based on the Separation of Axis Theorem (SAT).
 */
class SatDetector implements NarrowphaseDetector {
  
  /** See [NarrowphaseDetector.detectCollision]. */
  bool detectCollision (DynamicBody body1,
                        DynamicBody body2,
                        [Vector penetration]) {
    Collidable c1 = body1.collidable;
    Collidable c2 = body2.collidable;
    
    if (c1 is CollidableCircle && 
        c2 is CollidableCircle) {
      return _detectCircleCollision(c1 as CollidableCircle, body1,
                                    c2 as CollidableCircle, body2,
                                    penetration);
    }
    
    Vector2 normal = new Vector2();
    num overlap = 0.0;
    bool firstPass = true;
    
    List<Vector2> foci1 = new List<Vector2>();
    c1.getFoci(foci1, body1);
    
    List<Vector2> foci2 = new List<Vector2>();
    c2.getFoci(foci2, body2);
    
    List<Vector2> axes = new List<Vector2>();
    c1.getAxes(axes, foci2, body1);
    c2.getAxes(axes, foci1, body2);
    
    if (axes.isEmpty) {
      // No axes; and consequently no collision.
      return false;
    }
    
    // Go through the axes of the collidables, and look for a non-overlapping axis.
    for (Vector2 axis in axes) {
      if (!axis.isNull()) {
        Interval i1 = c1.project(axis, body1);
        Interval i2 = c2.project(axis, body2);
        
        if (!i1.overlap(i2)) {
          return false;
        } else if (penetration != null) {
          num currentOverlap = i1.getOverlap(i2);
          if (i1.contains(i2) ||
              i2.contains(i1)) {
            num max = (i1.max - i2.max).abs();
            num min = (i1.min - i2.min).abs();
            
            if (max > min) {
              axis = -axis;
              currentOverlap += min;
            } else {
              currentOverlap += max;
            }
          }
          
          if (currentOverlap < overlap || firstPass) {
            firstPass = false;
            overlap = currentOverlap;
            normal = axis;
          }
        }
      }
    }
    
    if (penetration != null) {
      Vector2 direction = body2.position - body1.position;
      if (direction.dot(normal) < 0.0) {
        normal = -normal;
      }
      
      penetration.clone(normal.normalized()*overlap);
    }
    
    return true;
  }
  
  /** Special treatment of circle-to-circle collision detection. */
  static bool _detectCircleCollision (CollidableCircle c1,
                                      DynamicBody body1,
                                      CollidableCircle c2,
                                      DynamicBody body2,
                                      [Vector2 penetration]) {
    Vector2 normal = (body2.position - body1.position);
    num radiusSum = c1.radius + c2.radius;
    if (normal.lengthSquared < radiusSum*radiusSum) {
      if (penetration != null) {
        penetration.clone(normal.normalized()*(radiusSum - normal.length));
      }
      return true;
    }
    return false;
  }
}
